//
//  CTVerificationViewController.m
//  ConstellationTalk_0.1
//
//  Created by riley on 15/4/20.
//  Copyright (c) 2015年 riley chu. All rights reserved.
//

#import "CTVerificationViewController.h"
#import "CTRegisterViewController.h"
#import "CTResetPasswordViewController.h"
#import "CTUserAgreementViewController.h"

//logic
#import "CTVerificationLogic.h"

//view
#import "CTVerificationView.h"

//function
#import "CTAppLanguage.h"
#import "CTDebugManager.h"
#import "CTTextManager.h"
#import "CTRemindView.h"
#import "CTActivitorView.h"
#import "CTReachability.h"
#import "CTGenRequestData.h"
#import "CTUser.h"
#import "MobClick.h"

//tool
#import "CRSA.h"
#import "SectionsViewController.h"
#import <SMS_SDK/SMS_SDK.h>

@interface CTVerificationViewController ()<CTVerificationLogicDelegate,CTVerificationViewDelegate,SecondViewControllerDelegate>
{
    CTVerificationView * verificationView;
    CTVerificationLogic * verificationLogic;
    
    SectionsViewController * sectionsVC;
    
    NSString * phoneNumber;
    NSString * codeStr;
    NSString * zoneStr;
    NSMutableArray * areaArray;
    
    CTActivitorView * acView;
}
@end

@implementation CTVerificationViewController

@synthesize registerType;

- (void)dealloc
{
    [verificationView removeFromSuperview];
    verificationView = nil;
    verificationLogic = nil;
    verificationView.delegate = nil;
    acView = nil;
    
    areaArray = nil;
    phoneNumber = nil;
    codeStr = nil;
    zoneStr = nil;
    
    sectionsVC = nil;
    
    [CTDebugManager showDebugLogInfo:@"dealloc : CTVerificationViewController Is Removed!!!"];
}

- (instancetype)init
{
    self = [super init];
    if (self) {
        verificationLogic = [[CTVerificationLogic alloc] init];
        verificationLogic.delegate = self;
        
        zoneStr = @"86";
    }
    return self;
}
-(void)viewDidAppear:(BOOL)animated
{
    //统计
    [MobClick beginLogPageView:@"CTVerificationViewController"];
    [super viewDidAppear:animated];
}

-(void)viewWillDisappear:(BOOL)animated
{
    //统计
    [MobClick endLogPageView:@"CTVerificationViewController"];
    [super viewWillDisappear:animated];
}

-(void)viewDidLoad
{
    verificationView = [[CTVerificationView alloc] init];
    verificationView.delegate = self;
    [self.view addSubview:verificationView];
    
    if (registerType == CTVerificationTypeMobileRegister) {
        verificationView.pageType = CTVerificationPageRegister;
    }
    else if(registerType == CTVerificationTypeResetPassword)
    {
        verificationView.pageType = CTVerificationPageResetPassword;
    }
    
    
    //获取支持的地区列表
    [SMS_SDK getZone:^(enum SMS_ResponseState state, NSArray *array)
     {
         if (1==state)
         {
             //区号数据
            
             areaArray = [NSMutableArray arrayWithArray:array];
             
             sectionsVC = [[SectionsViewController alloc] init];
             sectionsVC.delegate = self;
             [sectionsVC setAreaArray:areaArray];
             
         }
         else if (0==state)
         {
             
         }
         
     }];
    
}


#pragma mark - view delegate

-(void)verificationCodeAction:(CTVerificationView *)view
{

    if ([[CTTextManager shareInstance] isBlankString:phoneNumber] == YES) {
        CTRemindView * remindView = [[CTRemindView alloc] init];
        [remindView showRemindViewOn:self.view withRemindWord:[CTAppLanguage localizedStringForKey:@"remindView_login_c" withValue:nil withTable:@"Language"]];
        return;
    }
    if ([[CTTextManager shareInstance] isBlankString:zoneStr] == YES) {
        CTRemindView * remindView = [[CTRemindView alloc] init];
        [remindView showRemindViewOn:self.view withRemindWord:[CTAppLanguage localizedStringForKey:@"remindView_login_f" withValue:nil withTable:@"Language"]];
        return;
    }
    
    //监测网络
    if ([self checkNetworkState] == NO)return;

    
    [verificationLogic verificationTimerStatrt:phoneNumber area:zoneStr];
}

-(void)verifyAction:(CTVerificationView *)view
{
    
    if ([[CTTextManager shareInstance] isBlankString:phoneNumber] == YES || phoneNumber.length == 1) {
        CTRemindView * remindView = [[CTRemindView alloc] init];
        [remindView showRemindViewOn:self.view withRemindWord:[CTAppLanguage localizedStringForKey:@"remindView_login_c" withValue:nil withTable:@"Language"]];
        return;
    }
    
    if ([[CTTextManager shareInstance] isBlankString:codeStr] == YES || codeStr.length == 1) {
        CTRemindView * remindView = [[CTRemindView alloc] init];
        [remindView showRemindViewOn:self.view withRemindWord:[CTAppLanguage localizedStringForKey:@"remindView_login_i" withValue:nil withTable:@"Language"]];
        return;
    }
    
    //监测网络
    if ([self checkNetworkState] == NO)return;
    
    
    [self showRemindView];
    
    
    
    [verificationLogic verificationRequest:[CTGenRequestData genVerificationRequestItemPhoneNumber:phoneNumber] verifyCode:codeStr successCompletionHandler:^{
        dispatch_async(dispatch_get_main_queue(), ^{
            [acView removeActivitorView];
            
            NSString * created = [CTUser userCreated];
            if (registerType == CTVerificationTypeMobileRegister) {
                if ([created isEqualToString:@"1"]) {
                    //已注册
                    CTRemindView * remindView = [[CTRemindView alloc] init];
                    [remindView showRemindViewOn:self.view withRemindWord:[CTAppLanguage localizedStringForKey:@"remindView_login_o" withValue:nil withTable:@"Language"]];
                }
                else
                {
                    //未注册
                    CTRegisterViewController * registerVC = [[CTRegisterViewController alloc] init];
                    registerVC.phoneNumber = phoneNumber;
                    [self.navigationController pushViewController:registerVC animated:YES];
                }
                
            }
            else if (registerType == CTVerificationTypeResetPassword)
            {
                if ([created isEqualToString:@"1"]) {
                    //已注册
                    CTResetPasswordViewController * resetVC = [[CTResetPasswordViewController alloc] init];
                    resetVC.phoneNumber = phoneNumber;
                    [self.navigationController pushViewController:resetVC animated:YES];
                }
                else
                {
                    //未注册
                    CTRemindView * remindView = [[CTRemindView alloc] init];
                    [remindView showRemindViewOn:self.view withRemindWord:[CTAppLanguage localizedStringForKey:@"remindView_login_p" withValue:nil withTable:@"Language"]];
                    
                }
                
            }else
            {
                
            }
        });
    } failedHandler:^{
        dispatch_async(dispatch_get_main_queue(), ^{
            [acView removeActivitorView];
            CTRemindView * remindView = [[CTRemindView alloc] init];
            [remindView showRemindViewOn:self.view withRemindWord:[CTAppLanguage localizedStringForKey:@"remindView_login_n" withValue:nil withTable:@"Language"]];
        });
    }];
    
    
}
-(void) verificationViewPhoneTextFieldText:(NSString *)text  registerView:(CTVerificationView *) View
{
    phoneNumber = text;
}
-(void) verificationViewInputTextFieldText:(NSString *)text  registerView:(CTVerificationView *) View
{
    codeStr = text;
}

//更换国家按钮
-(void) verificationViewStateButton:(CTVerificationView *) registerView
{
    
    [self presentViewController:sectionsVC animated:YES completion:^{
        
    }];
}
//返回按钮
-(void) verificationViewBackButton:(CTVerificationView *)registerView
{
    [verificationLogic deallocVerficationLogic];
    [self.navigationController popViewControllerAnimated:YES];
}

-(void)verificationProBtnAction:(CTVerificationView *)view
{
    CTUserAgreementViewController * userAgreementVC = [[CTUserAgreementViewController alloc] init];
    userAgreementVC.showType = CTUserAgreementViewControllerShowTypePresent;
    [self presentViewController:userAgreementVC animated:YES completion:^{
        
    }];
}


#pragma mark section view controller delegate

-(void)setSecondData:(CountryAndAreaCode *)data
{
    verificationView.areaName = data.countryName;
    verificationView.areaCode = data.areaCode;
    
    zoneStr = data.areaCode;
}


#pragma mark - logic delegate

-(void)timerDidStart:(CTVerificationLogic *)logic withTime:(int)sec
{
    verificationView.timerText = [NSString stringWithFormat:@"%ds",sec];
}

-(void)timerDidFinish:(CTVerificationLogic *)logic
{
    verificationView.timerText = [CTAppLanguage localizedStringForKey:@"verificationView_getVerificationCode" withValue:nil withTable:@"Language"];
}

-(void)sendMessageSuccess:(CTVerificationLogic *)logic
{
    dispatch_async(dispatch_get_main_queue(), ^{
        [acView removeActivitorView];
        CTRemindView * remindView = [[CTRemindView alloc] init];
        [remindView showRemindViewOn:self.view withRemindWord:[CTAppLanguage localizedStringForKey:@"remindView_login_h" withValue:nil withTable:@"Language"]];
    });
}

-(void)sendMessageFailed:(CTVerificationLogic *)logic
{
    dispatch_async(dispatch_get_main_queue(), ^{
//        [acView removeActivitorView];
//        CTRemindView * remindView = [[CTRemindView alloc] init];
//        [remindView showRemindViewOn:self.view withRemindWord:[CTAppLanguage localizedStringForKey:@"remindView_login_g" withValue:nil withTable:@"Language"]];
    });
}


#pragma mark - main thread update



-(void)showRemindView
{
    acView = [[CTActivitorView alloc] init];
    [acView showActivitorViewOn:self.view];
}

#pragma mark - check net work state -
-(BOOL)checkNetworkState
{
    NSString * descri;
    CTRemindView * remindView;
    
    CTNetWorkReachabilityStatus  status = [CTReachability judegeCurrentNetWorkStatus];
    switch (status) {
        case CTNetWorkReachabilityStatusUnknown:
            descri = [CTAppLanguage localizedStringForKey:@"remindView_login_networkUnknow" withValue:nil withTable:@"Language"];
            remindView = [[CTRemindView alloc] init];
            [remindView showRemindViewOn:self.view withRemindWord:descri];
            return NO;
            break;
        case CTNetWorkReachabilityStatusNotReachable:
            descri = [CTAppLanguage localizedStringForKey:@"remindView_login_networkReachable" withValue:nil withTable:@"Language"];
            remindView = [[CTRemindView alloc] init];
            [remindView showRemindViewOn:self.view withRemindWord:descri];
            return NO;
            break;
        default:
            break;
    }
    return YES;
}

-(void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    [CTDebugManager showDebugLogInfo:@"CTVerificationViewController内存警告!!!"];
}

@end
